<!-- 区域 -->

<template>
  <div :key="one.roleType">
    <FormSlot :label="`${CORE.MAP.REGION}权限`" noMargin />

    <FormSlot :label="`${CORE.MAP.REGION}权限`" :bind="`${bindKey}Str`" noLabel :required="required">
      <EasyScroll :height="height" class="el-input__inner">
        <el-tree v-if="required" ref="tree" v-bind="treeProps" @check="toChange" />
      </EasyScroll>
    </FormSlot>
  </div>
</template>

<script>
// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'

const getLeafIdList = (leafIdList, tree) => {
  tree.forEach(({ children, id }) => {
    if (children.length) getLeafIdList(leafIdList, children)
    else leafIdList.push(id)
  })
  return leafIdList
}

// ============================== 导出组件 ============================== //

export default {
  /**
   * 名称定义 (实际使用名称)
   */
  name: 'MyRegion',

  /**
   * 混入列表 (配置选项合并)
   */
  mixins: [CORE.mixWeb()],

  /**
   * 计算属性 (慎用箭头函数)
   */
  computed: {
    /**
     * 高度
     */
    height: () => 400,

    /**
     * 绑定键
     */
    bindKey: () => 'regionId',

    /**
     * 结构树数据
     */
    treeData() {
      return CORE.REGION.TREE
    },

    /**
     * 是否必填
     */
    required() {
      return this.one.roleType === 1
    },

    /**
     * 结构树属性
     */
    treeProps() {
      return {
        data: this.treeData,
        nodeKey: 'id',
        props: { children: 'children', label: 'name' },
        indent: 32,
        showCheckbox: true,
        defaultExpandedKeys: this.treeData.map((item) => item.id),
      }
    },

    /**
     * 所有叶子节点列表
     */
    allLeafIdList() {
      return getLeafIdList([], this.treeData)
    },

    /**
     * 已选叶子节点列表
     */
    leafIdList() {
      const { one, bindKey, allLeafIdList } = this
      return one[bindKey].filter((id) => allLeafIdList.includes(id))
    },
  },

  /**
   * 监听属性 (深度 deep 首次 immediate)
   */
  watch: {
    /**
     * 监听弹窗可见
     */
    visible(visible) {
      if (visible && ['add', 'edit', 'show'].includes(this.modal)) this.init()
    },
  },

  /**
   * 挂载完成 (先抽取再调用)
   */
  mounted() {
    this.init()
  },

  /**
   * 本地方法 (轻量重要在前)
   */
  methods: {
    /**
     * 初始化
     */
    init() {
      const { tree } = this.$refs || {}
      tree && tree.setCheckedKeys(this.leafIdList)
    },

    /**
     * 选择改变
     */
    toChange(node, { halfCheckedKeys, checkedKeys }) {
      const { one, bindKey } = this
      one[bindKey] = [...halfCheckedKeys, ...checkedKeys]
      one[`${bindKey}Str`] = one[bindKey].join()
    },
  },
}
</script>
